﻿using System;
using System.Collections.Generic;
using RobotGerchik.DataClass;
using System.IO;
using System.Xml.Serialization;
using System.Collections.ObjectModel;
using RobotGerchik.DataClass.Gerchik;

namespace RobotGerchik.Config
{
    class XMLHistory
    {
        public static String FILENAME_GerchikRobots = "\\GerchikRobotItems.xml";

        public static object GetXmlData(string filename)
        {
            String path = Environment.GetFolderPath(Environment.SpecialFolder.CommonDocuments) + "\\RobotGerchik";

            if (!Directory.Exists(path))
            {
                System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(path);
                dir.Create();
            }

            if (filename == FILENAME_GerchikRobots)
            {
                try
                {
                    XmlSerializer reader = new XmlSerializer(typeof(List<GechikRobotItem>));
                    StreamReader file = new StreamReader(path + filename);
                    List<GechikRobotItem> result = new List<GechikRobotItem>();
                    result = (List<GechikRobotItem>)reader.Deserialize(file);

                    ObservableCollection<GechikRobotItem> res = new ObservableCollection<GechikRobotItem>();
                    for (int i = 0; i < result.Count; i++)
                    {
                        result[i].IsRun = false;
                        result[i].CurrentAttempt = 0;
                        if (result[i].AttemptAmount == 0)
                            result[i].AttemptAmount = 1;
                        res.Add(result[i]);
                    }

                    return res;

                }
                catch (Exception)
                {
                    return new ObservableCollection<GechikRobotItem>();
                }
            }

            return null;
        }

        public static void SetXmlData(string filename, object List)
        {
            String path = Environment.GetFolderPath(Environment.SpecialFolder.CommonDocuments) + "\\RobotGerchik";

            if (!Directory.Exists(path))
            {
                System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(path);
                dir.Create();
            }
            if (filename == FILENAME_GerchikRobots)
            {
                try
                {
                    XmlSerializer write = new System.Xml.Serialization.XmlSerializer(typeof(List<GechikRobotItem>));
                    using (StreamWriter file = new System.IO.StreamWriter(path + filename))
                        write.Serialize(file, List);
                }
                catch (Exception ex)
                {
                    //cfg.SetLog(ex.ToString(), new XMLHistory().GetType(), MethodBase.GetCurrentMethod());
                }
            }
        }
    }
}
